package controller.article;

import controller.BaseServlet;
import model.Article;
import model.User;
import org.apache.commons.beanutils.BeanUtils;
import pojo.PageEntity;
import service.ArticleService;
import service.FavoriteService;
import service.impl.ArticleServiceImpl;
import service.impl.FavoriteServiceImpl;
import utils.JsonUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@WebServlet("/article/*")
public class ArticleServlet extends BaseServlet {

    private ArticleService service = new ArticleServiceImpl();
    private FavoriteService favoriteService = new FavoriteServiceImpl();

    public void findPage(HttpServletRequest req, HttpServletResponse resp){
        try{
            Map<String, String> params = getParams(req);
            Integer currPage;
            //当前页
            if(params.get("currPage") == null || params.get("currPage").equals("")) {
                currPage = 1;
            }else{
                currPage = Integer.parseInt(params.get("currPage"));
            }
            String title = params.get("title");
            if(title == null){
                title = "";
            }
            PageEntity<Article> pageData = service.findPage(currPage, title);
            req.setAttribute("pageData",pageData);
            req.setAttribute("title",title);
            req.getRequestDispatcher("/view/article").forward(req,resp);

        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public void add(HttpServletRequest req, HttpServletResponse resp){
        try {
            Article article = new Article();
            BeanUtils.populate(article, req.getParameterMap());
            User user = (User)req.getSession().getAttribute("loginUser");
            article.setUserId(user.getId());
            if(user.getRealName() == null || user.getRealName().equals("")){
                article.setPublishRealName(user.getUsername());
            }else{
                article.setPublishRealName(user.getRealName());
            }
            service.add(article);
            resp.sendRedirect(req.getContextPath() + "/article/findPage?currPage=1");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void articleDetail(HttpServletRequest req, HttpServletResponse resp){
        try {
            Map<String, String> params = getParams(req);
            Integer artId = Integer.valueOf(params.get("id"));
            User user = (User)req.getSession().getAttribute("loginUser");
            Article article = service.findById(artId);
            article.setBrowseCount(article.getBrowseCount() + 1);
            //更新浏览数
            if(params.get("flag") == null){
                service.update(article);
            }
            //查询出我关注的人里面有哪些收藏了这篇文章
            List<Map<String, Object>> userFavorite = favoriteService.findByUserFavorite(user.getId(), artId);
            // 查询我是否有关注过指定文章
            Boolean isFavorite = favoriteService.findIsFavorite(user.getId(), artId);
            // 查询文章收藏数
            Integer favoriteCount = favoriteService.findByFavoriteCountByArticleId(artId);
            // 文章信息
            req.setAttribute("article", article);
            // 是否有关注过这篇文章
            req.setAttribute("isFavorite", isFavorite);
            // 我关注的人里面有哪些关注过这篇文章
            req.setAttribute("userFavorite", userFavorite);
            // 收藏数
            req.setAttribute("favoriteCount", favoriteCount);
            req.getRequestDispatcher("/view/articleDetail").forward(req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void favorite(HttpServletRequest req, HttpServletResponse resp){
        try{
            Map<String, String> params = getParams(req);
            Boolean isFavorite = Boolean.parseBoolean(params.get("isFavorite"));
            Integer artId = Integer.valueOf(params.get("id"));
            User user = (User)req.getSession().getAttribute("loginUser");
            if(isFavorite){
                // 取消收藏
                favoriteService.unFavorite(user.getId(), artId);
            }else{
                favoriteService.favorite(user.getId(), artId);
            }
            JsonUtil.writerObjToString(resp, 200);
        }catch (Exception e){
            JsonUtil.writerObjToString(resp, 500);
            e.printStackTrace();
        }
    }

    public void favoritePage(HttpServletRequest req, HttpServletResponse resp){
        try {
            Map<String, String> params = getParams(req);
            String title = params.get("title");
            User user = (User)req.getSession().getAttribute("loginUser");
            Integer currPage;
            //当前页
            if(params.get("currPage") == null || params.get("currPage").equals("")) {
                currPage = 1;
            }else{
                currPage = Integer.parseInt(params.get("currPage"));
            }
            if (title == null) {
                title = "";
            }
            PageEntity<Article> pageData = favoriteService.favoritePage(currPage, title, user.getId());
            List<Article> data = pageData.getData();
            List<Integer> count = new ArrayList<>();
            for(int i = 0; i < data.size(); i++){
                Integer artId = data.get(i).getId();
                count.add(i, favoriteService.findByFavoriteCountByArticleId(artId));
            }
            req.setAttribute("pageData", pageData);
            req.setAttribute("count",count);
            // 用于回显搜索条件
            req.setAttribute("title", title);
            req.getRequestDispatcher("/view/articleCollect").forward(req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
